<?php

namespace App\Http\Controllers\Myorder;

use App\Http\Controllers\Service\ServiceController;
use App\Models\OrderModel;
use Illuminate\Http\Request;
use App\Http\Components\UserComponent;
use App\Http\Components\MessageComponent;
use App\Models\ServiceModel;
use App\Models\UserAccountModel;
use App\Models\UserProfileModel;
use App\Models\DataConfigModel;
use App\library\UploadFile;
use App\Models\LogOrderModel;


/**
 * 接单
 */
class ReceiveOrderController extends ServiceController{

    public function __construct(){
        parent::__construct();
    }

    /**
     * 版本控制，对应app版本跳转对应接口
     * @param Request $request
     * @author paulLu
     */
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{
                return $this->receive_order($request);
            }catch(\Exception $e){
                return $this->json('0','系统错误');
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     * 接单
     */
    public function receive_order(Request $request){
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $customAttr = [
            'order_id'=>'订单号',
        ];
        $this->validate($request, [
            'order_id'=>'required',
        ],[ ], $customAttr);
        $status = 2;
        $order_id = $request->input('order_id');
        $order = OrderModel::where("order_id",$order_id)
            ->where('order.user_id','=',$user_id)
            ->first();

        if($order){
            $previous_status = $order->status;
            if($order->status != 1){
                return $this->json('0','订单状态有误!');
            }
            $order->status = $status;
            $order->uptime = date("Y-m-d H:i:s");
            $result = $order->saveOrFail();
            if($result){
                $log_order = new LogOrderModel();
                $log_order->save_log($user_id,$order_id,$previous_status,$status);
                $seller_user = UserProfileModel::where('user_id',$order->user_id)->first()->toArray();
                MessageComponent::unite_push('seller_receive_order',array('user_id'=>$order->pay_user_id,'seller_name'=>$seller_user['nick_name'],'order_id'=>$order_id));
                return $this->json('1','操作成功');
            }else{
                return $this->json('0','操作失败');
            }
        }else{
            return $this->json('0','该订单不存在!');
        }
    }
}